package com.example.config.resp;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class RtnErrUtil {
	
	private RtnErrUtil() {}
	
	private static final Logger LOG = LoggerFactory.getLogger(RtnErrUtil.class);
	
	@SuppressWarnings("rawtypes")
	public static ResponseMessage handle(Exception e){
		LOG.error(ExceptionUtils.getFullStackTrace(e));
		ResponseMessage message = new ResponseMessage();
		if (e instanceof ConstraintViolationException) {
			ConstraintViolationException cve = (ConstraintViolationException) e;
			Set<ConstraintViolation<?>> set = cve.getConstraintViolations();
			ConstraintViolation c = set.iterator().next();
			String propertyPath = c.getPropertyPath().toString();
			String field = propertyPath.substring(propertyPath.lastIndexOf('.') + 1);
			String rtnMsg = RtnCode.CODEMAP.get(c.getMessage());
			if(RtnCode.R10016.equals(c.getMessage()) || RtnCode.R10017.equals(c.getMessage())){
				rtnMsg = String.format(rtnMsg, field);
			}
			message.setRtnCode(c.getMessage());
			message.setRtnMsg(rtnMsg);
		} else if (e instanceof UsernameNotFoundException) {
			message.setRtnCode(RtnCode.R10001);
			message.setRtnMsg(RtnCode.CODEMAP.get(RtnCode.R10001));
		} else {
			message.setRtnCode(RtnCode.R10001);
			message.setRtnMsg(RtnCode.CODEMAP.get(RtnCode.R10001)+" ("+e.getMessage()+")");
		}
		return message;
	}
	
}
